<!-- 使用 type="home" 属性设置首页，其他页面不需要设置，默认为page；推荐使用json5，更强大，且允许注释 -->
<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '新增收货地址',
    navigationBarRightButton: {
      hide: true,
    },
  },
}
</route>
<template>
  <view
    class="w-full h-full bg-white overflow-hidden box-border"
    :style="{ paddingTop: safeAreaInsets?.top + 'px' }"
  >
    <view class="w-full h-full home-container">
      <wd-navbar @click-left="handleClickLeft">
        <template #title>
          <text class="text-gray-333 font-size-36 font-500">新增收货地址</text>
        </template>
        <template #left>
          <wd-icon
            name="chevron-left"
            class="text-gray-333 font-size-44"
            @click="pagesBack"
          ></wd-icon>
        </template>
      </wd-navbar>
      <view class="w-full h-full p-x-28 p-y-32 home-content">
        <view class="w-full flex justify-start items-center bdr-bottom-2-#F5F5F5 p-y-32">
          <view class="wr-210">
            <text class="text-gray-333 font-size-32 font-400">收货人</text>
          </view>
          <wd-input
            v-model="modelForm.name"
            no-border
            placeholderClass="font-size-32 font-400"
            placeholder="请输入收货人姓名"
          ></wd-input>
        </view>
        <view class="w-full flex justify-start items-center bdr-bottom-2-#F5F5F5 p-y-32">
          <view class="wr-210">
            <text class="text-gray-333 font-size-32 font-400">手机号</text>
          </view>
          <wd-input
            v-model="modelForm.mobile"
            no-border
            placeholderClass="font-size-32 font-400"
            placeholder="请输入收货人手机号"
          ></wd-input>
        </view>
        <view class="w-full flex justify-start items-center bdr-bottom-2-#F5F5F5 p-y-32">
          <view class="wr-210">
            <text class="text-gray-333 font-size-32 font-400">所在地区</text>
          </view>
          <wd-input
            v-model="modelForm.webAddress"
            no-border
            use-suffix-slot
            placeholderClass="font-size-32 font-400"
            placeholder="请输入收货人所在地区"
            custom-input-class="w-full"
            @focus="handleChooseRegion"
          >
            <template #suffix>
              <wd-col-picker
                ref="colPicker"
                v-model="value"
                title="请选择所在地区"
                :columns="area"
                use-default-slot
                :column-change="columnChange"
                @confirm="handleConfirm"
              >
                <view class="wr-44 hr-44">
                  <image width="100%" height="100%" src="../../static/images/icons/address.png" />
                </view>
              </wd-col-picker>
            </template>
          </wd-input>
        </view>
        <view class="w-full flex justify-start items-center bdr-bottom-2-#F5F5F5 p-y-32">
          <view class="wr-210">
            <text class="text-gray-333 font-size-32 font-400">详细地址</text>
          </view>
          <wd-input
            v-model="modelForm.address"
            no-border
            placeholderClass="font-size-32 font-400"
            placeholder="请输入收货人详细地址"
          ></wd-input>
        </view>
        <view
          class="w-full flex justify-between items-center bdr-bottom-2-#F5F5F5 p-y-32"
          v-if="!editInfo"
        >
          <view>
            <text class="text-gray-333 font-size-32 font-400">设为默认收货地址</text>
          </view>
          <wd-switch v-model="modelForm.isDefault" :size="'48rpx'" />
        </view>
        <view class="w-full hr-88 flex justify-center items-center mg-t-110">
          <wd-button size="small" @click="handleSubmit">
            <text class="font-size-32 font-500 text-white">保存</text>
          </wd-button>
        </view>
      </view>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { addAddress, getAreaList, updateAddress } from '@/service/my/my'
defineOptions({
  name: 'ShareLedger',
})
const { safeAreaInsets } = uni.getSystemInfoSync()
const handleClickLeft = () => {}
const value = ref<any[]>([])
const area = ref<any[]>([])
const areaData = ref<any>({})
const columnChange = ({ selectedItem, resolve, finish }) => {
  if (areaData.value[selectedItem.value]) {
    resolve(
      Object.keys(areaData.value[selectedItem.value]).map((key) => {
        return {
          value: key,
          label: areaData.value[selectedItem.value][key],
        }
      }),
    )
  } else {
    finish()
  }
}
const handleConfirm = (data: any) => {
  const selectedItems = data.selectedItems
  let region = ''
  for (let i = 0; i < selectedItems.length; i++) {
    const item = selectedItems[i]
    if (i === 0) {
      modelForm.value.province = item.label
    } else if (i === 1) {
      modelForm.value.city = item.label
    } else if (i === 2) {
      modelForm.value.district = item.label
    }
    region += item.label + ' '
  }
  modelForm.value.webAddress = region
}

const pagesBack = () => {
  uni.navigateBack()
}
const modelForm: any = ref({
  webAddress: '', // 前端使用字段
  name: '', // 必填
  mobile: '', // 必填
  province: '', // 必填
  city: '', // 必填
  district: '', // 必填
  address: '', // 必填
  isDefault: 1, // 非必填(默认0) 是否设置默认:0=否,1=是
})
const colPicker = ref<any>(null)
const handleChooseRegion = () => {
  colPicker.value.open()
}
const handleSubmit = () => {
  if (editInfo.value) {
    modelForm.value.type = 0
    modelForm.value.id = editInfo.value.id
    updateAddress(modelForm.value).then(() => {
      uni.showToast({
        title: '修改成功',
        icon: 'none',
        duration: 2000,
      })
      uni.navigateTo({
        url: '/pages/location/listLocation',
      })
    })
  } else {
    delete modelForm.value.webAddress
    modelForm.value.isDefault = modelForm.value.isDefault ? 1 : 0
    addAddress(modelForm.value).then(() => {
      uni.showToast({
        title: '保存成功',
        icon: 'none',
        duration: 2000,
      })
      uni.navigateTo({
        url: '/pages/location/listLocation',
      })
    })
  }
}
onLoad(() => {
  getArea()
})
const editInfo: any = ref(null)
onShow(() => {
  const editData: any = uni.getStorageSync('editAddress')
  if (editData !== '{}') {
    const editForm: any = JSON.parse(editData)
    modelForm.value.name = editForm.name
    modelForm.value.mobile = editForm.mobile
    modelForm.value.province = editForm.province
    modelForm.value.city = editForm.city
    modelForm.value.district = editForm.district
    modelForm.value.address = editForm.address.split(' ')[editForm.address.split(' ').length - 1]
    modelForm.value.isDefault = Number(editForm.isDefault) !== 0
    modelForm.value.webAddress = editForm.province + ' ' + editForm.city + ' ' + editForm.district
    editInfo.value = editForm
  } else {
    editInfo.value = null
  }
})
const getArea = () => {
  getAreaList().then((res: any) => {
    if (res.data) {
      const cities: any = res.data.cities
      const districts: any = res.data.districts
      const provinces: any = res.data.provinces
      const areaObject: any = {}
      const netAreaData: any = [...cities, ...districts, ...provinces]
      netAreaData.forEach((item: any) => {
        if (item.pid == null) {
          if (areaObject['86']) {
            areaObject['86'][item.id] = item.name
          } else {
            areaObject['86'] = {
              [item.id]: item.name,
            }
          }
        } else {
          if (areaObject[item.pid]) {
            areaObject[item.pid][item.id] = item.name
          } else {
            areaObject[item.pid] = {
              [item.id]: item.name,
            }
          }
        }
      })
      areaData.value = areaObject
      area.value = [
        Object.keys(areaData.value[86]).map((key) => {
          return {
            value: key,
            label: areaData.value[86][key],
          }
        }),
      ]
    }
  })
}
</script>

<style scoped lang="scss">
.home-container {
  position: relative;
  z-index: 1;
}
.home-content {
  height: calc(100% - var(--wot-navbar-height, 88rpx));
  overflow: auto;
}
::v-deep .wd-button {
  width: 100% !important;
  height: 100% !important;
}
::v-deep .wd-input {
  width: calc(100% - 210rpx);
}
::v-deep .wd-action-sheet__popup {
  border-radius: 16rpx;
}
::v-deep .wd-action-sheet__header {
  height: 98rpx;
  line-height: 98rpx;
  border-bottom: 2rpx solid #f5f5f5;
}
::v-deep .wd-action-sheet__close {
  top: 32rpx;
}
</style>
